package com.smartrobot.smartrobot.adapter;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.siyamed.shapeimageview.CircularImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.smartrobot.smartrobot.Common.Common;
import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.activity.ActiveActivity;
import com.smartrobot.smartrobot.activity.ShowBigPicActivity;
import com.smartrobot.smartrobot.logToSdCard.LogToSd;
import com.smartrobot.smartrobot.util.Active;
import com.smartrobot.smartrobot.util.FileUtil;
import com.smartrobot.smartrobot.util.ImageLoaderApi;
import com.smartrobot.smartrobot.util.User;
import com.smartrobot.smartrobot.view.ExListView;
import com.smartrobot.smartrobot.view.ToastCustom;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;

/**
 * Created by Administrator on 2014/12/23.
 */
public class ActiveListViewAdapter extends BaseAdapter implements AbsListView.OnScrollListener {


    private Context context;
    private List<Active> list;
    private ImageLoader imageLoader;
    private ExListView listView;
    private boolean isScroll = false;


    public ActiveListViewAdapter(Context context, List<Active> activeList, ExListView _listView) {

        this.context = context;
        ImageLoaderApi.initImageLoaderApiActivePic(context);
        imageLoader = ImageLoader.getInstance();
        list = activeList;
        listView = _listView;

    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {

        ViewHolder holder;

        if (convertView == null) {
            //新建一个holder
            convertView = LayoutInflater.from(context).inflate(R.layout.page_friend_active_adapter_item, viewGroup, false);
            holder = new ViewHolder();

            holder.photo = (CircularImageView) convertView.findViewById(R.id.active_adapter_item_head);
            holder.nickName = (TextView) convertView.findViewById(R.id.active_adapter_item_nickname);
            holder.sharePic = (ImageView) convertView.findViewById(R.id.active_adapter_item_share_pic);
            holder.content = (TextView) convertView.findViewById(R.id.active_adapter_item_say);
            holder.time = (TextView) convertView.findViewById(R.id.active_adapter_item_send_time);

            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        //初始化所有view
        Active active = list.get(position);
        if (active.getuNickName() != null && !active.getuNickName().equals(""))
            holder.nickName.setText(active.getuNickName());
        else
            holder.nickName.setText(active.getuAccount());

        holder.content.setText(active.getContent());
        holder.time.setText(active.getTime());


        imageLoader.displayImage(Common.baseUrl + active.getuHead(), holder.photo, ImageLoaderApi.getOptions());
        if (active.getFileUrl() != null && !active.getFileUrl().equals("")) {
            holder.sharePic.setVisibility(View.VISIBLE);
            imageLoader.displayImage(Common.baseUrl + active.getFileUrl(), holder.sharePic, ImageLoaderApi.getActivePicOptions());
            Log.e("=======================>", "  "+ Common.baseUrl + active.getFileUrl());

        } else {
            holder.sharePic.setVisibility(View.GONE);
        }


        holder.sharePic.setOnClickListener(new SharePicClick(position));

        return convertView;
    }

    public void notiOldDataChange(List<Active> list) {

        //通知改变数据
        this.list.addAll(list);
        notifyDataSetChanged();

    }

    public void notiNewSingleDataChange(List<Active> list) {

        //引用会改变内部值
        List<Active> temp = new ArrayList<Active>();
        temp.addAll(list);
        temp.addAll(this.list);
        this.list.clear();
        this.list.addAll(temp);
        notifyDataSetChanged();
        temp.clear();
        temp = null;//避免内存泄露

    }

    public void notiNewDataChange(List<Active> list) {

//        if (list.size() > 10) {//若是返回动态多余10条就改变动态
            //引用会改变内部值
            this.list.clear();
            this.list.addAll(list);
            notifyDataSetChanged();
//        } else {//若是少于十条就添加到新的里面去
//            list.addAll(this.list);
//            this.list.clear();
//            this.list.addAll(list);
//            notifyDataSetChanged();
//        }


    }


    public String getNewUpdateTime() {
            return "111111111111";
    }

    public String getOldUpdateTime() {
        if (list != null && list.size() > 0) {
            return list.get(list.size() - 1).getTimeResort();
        } else
            return "111111111111";//这个是最小时间
    }

    /**
     * 将数据保存起来
     *
     * @return
     */
    public List<Active> getList() {
        return this.list;
    }


    class ViewHolder {

        CircularImageView photo;
        TextView nickName;
        ImageView sharePic;
        TextView content;
        TextView time;


    }

    public void saveCircleToFile() {
        //只是保存十条数据到文件缓存中
        List<Active> saveList;
        if (this.list.size() > 10)
            saveList = this.list.subList(0, 10);
        else
            saveList = this.list;

        try {
            if (FileUtil.createFile(FileUtil.activeCircleCachePath + User.getInstance().getId() + User.getInstance().getPhone() + FileUtil.activeCircleFileEndName)) {
                FileUtil.writeJsonToFile(saveList, FileUtil.activeCircleCachePath + User.getInstance().getId() + User.getInstance().getPhone() + FileUtil.activeCircleFileEndName);
                Log.d("--------->", "保存成功");
                LogToSd.error("动态保存文件,保存成功!");
            } else {
                Log.e("--------->", "无法创建文件");
                LogToSd.error("动态保存文件,错误" + "无法创建文件夹");
            }
        } catch (Exception e) {
            Log.e("--------->", "无法找到文件");
            LogToSd.error("动态保存文件,错误：" + e.getMessage().toString());
        }
    }

    public void saveWorldToFile() {
        List<Active> saveList;
        if (this.list.size() > 10)
            saveList = this.list.subList(0, 10);
        else
            saveList = this.list;

        try {
            if (FileUtil.createFile(FileUtil.activeWorldCachePath + User.getInstance().getId() + User.getInstance().getPhone() + FileUtil.activeWorldFileEndName)) {
                FileUtil.writeJsonToFile(saveList, FileUtil.activeWorldCachePath + User.getInstance().getId() + User.getInstance().getPhone() + FileUtil.activeWorldFileEndName);
                Log.d("--------->", "保存成功");
            } else
                Log.e("--------->", "无法创建文件");
        } catch (IOException e) {
            Log.e("--------->", "无法找到文件");
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

        switch (scrollState) {
            case AbsListView.OnScrollListener.SCROLL_STATE_IDLE: //滑动后静止

                isScroll = false;
                listView.ToEnd(view);
                break;
            case AbsListView.OnScrollListener.SCROLL_STATE_FLING://手指离开后惯性滑动

                isScroll = true;
                listView.ToEnd(view);
                break;
            case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL://手指一直在滑动

                isScroll = true;
                listView.ToEnd(view);

                break;
        }

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        listView.setFirstItemIndex(firstVisibleItem);
    }

    /**
     * 监听点击事件，显示大图片
     */

    class SharePicClick implements View.OnClickListener {

        int pos;

        public SharePicClick(int pos) {
            this.pos = pos;
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()) {

                case R.id.active_adapter_item_share_pic:

                    Intent intent = new Intent();
                    intent.setClass(context, ShowBigPicActivity.class);
                    intent.putExtra("url", list.get(pos).getFileUrl());
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);

                    break;

            }
        }
    }
}
